package org.example.netty.mgt;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import org.example.netty.model.CustomMessage;
import org.example.netty.model.ExtendedChannelContext;
import org.example.netty.config.NettyEndpointConfig;
import org.example.netty.utils.SnowflakeIdGenerator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ServerConnectionManager implements ConnectionManager{
    private final ConcurrentMap<ChannelId, ExtendedChannelContext> channelContextMap = new ConcurrentHashMap<>();
    private final SnowflakeIdGenerator snowflakeIdGenerator;
    @Override
    public void putChannel(Channel channel){
        channelContextMap.put(channel.id(),new ExtendedChannelContext(channel));
    }
    @Override
    public void removeChannel(Channel channel){
        ExtendedChannelContext extendedChannelContext = channelContextMap.remove(channel);
        extendedChannelContext.close();
    }

    @Override
    public Channel getChannel(ChannelId channelId) {
        if (channelContextMap.get(channelId)==null){
            return null;
        }

        return channelContextMap.get(channelId).getChannel();
    }


    @Override
    public ExtendedChannelContext getExtendedChannelContext(ChannelId channelId) {
        return channelContextMap.get(channelId);
    }

    @Override
    public List<ExtendedChannelContext> getAllExtendedChannelContext() {
        return new ArrayList<>(channelContextMap.values());
    }


    public ServerConnectionManager(NettyEndpointConfig config) throws NettyEndpointConfig.ValueIsEmpty {
        if (config.getMachineId()!=0){
            this.snowflakeIdGenerator = new SnowflakeIdGenerator(config.getMachineId());
        }else {
            throw new NettyEndpointConfig.ValueIsEmpty("machineId不能为空");
        }
    }

    @Override
    public long generateRequestId() {
        return snowflakeIdGenerator.nextId();
    }

    @Override
    public NettyEndpointConfig getNettyConfig() {
        return null;
    }
    public CustomMessage syncSendMessage(CustomMessage message){
        for (Map.Entry<ChannelId, ExtendedChannelContext> entry : channelContextMap.entrySet()) {
            ExtendedChannelContext entryValue = entry.getValue();
            Channel channel = entryValue.getChannel();
            syncSendMessage(message,channel);
        }
        return null;
    }
    public CustomMessage syncSendMessage(CustomMessage message,Channel channel){
        CompletableFuture<CustomMessage> future = new CompletableFuture<>();
        long requestId = generateRequestId();
        channel.writeAndFlush(message);



        return null;
    }

}
